var rowIndex = "%^%%%%";
var regid = 0;
var flag = true;
var page;
var _fBillNo;
var gg;
var _fDetailID,_fBillNo,_fDate,_fSupplyName,_fTaxrate,_id;
var printids=[];
/*
* @Description: 操作事件
* @param :
*/
$("#printin").click(function(){
	var datas = $("#inTable").bootstrapTable('getSelections');//获取勾选的row
	if(datas==''){
		swal_Tips("请勾选");
		return false;
	}
	var flag = 1;
	var ids=[];
	$.each(datas,function(key,value){
		ids.push(value.id);
	});
	if(ids.length == 0){
		flag = 0;
		swal_Tips("请至少选择一个需要打印的物料项");
		return;
	}
	if(flag == 1){
		$('#printCardModal').modal('show');
		printids=ids;
	}
});
// 确认按钮
$('#printconfirm').click(function(){
	console.log($("#printtype option:selected").val());
	if($("#printtype option:selected").val()=='1'){
		window.open(pathUrl("OSL?ids="+printids+"&type=0"));
	}
	else if($("#printtype option:selected").val()=='2'){
		window.open(pathUrl("OSL?ids="+printids+"&type=1"));
	}else{
		window.open(pathUrl("OSL?ids="+printids+"&type=2"));
	}
})
// 取消按钮
$('#printcancel').click(function(){
	$('#printCardModal').modal('hide');
})
window.operateEvents = {
		'click .in' : function(e, value, row, index) {//替换按钮点击事件
			_id=row.id;
				$('#daoTable').bootstrapTable('destroy').bootstrapTable({
					url : pathUrl("poOrder/replacePoOrderList.action"),//请求后台的URL
					//height : $(window).height() - 200,//行高
					method : "POST",
					striped : true,
					cache : false,
//					editable:false,//开启编辑模式
					sidePagination : "server", // 分页方式：client客户端分页，server服务端分页（*）
					pagination : true,
					pageNumber : 1,
					pageSize : 10,
					pageList : [ 10, 30, 60, 100, 'ALL' ],
					dataExport : dataExport,
					showExport: true,
					colArr : colArr,
					exportDataType: "allServer",
					buttonsAlign:"right",  //按钮位置
					queryParams : function(params) {//传递参数
						var data= {};
						var orderBy = params.sort + " " + params.order;      //排序列名
						if(params.sort==undefined){
							orderBy = "fDate desc";
						}
						data.offset = params.offset +1;
						data.row = params.limit,
						data.sqlStr = sqlCombine;
						data.orderBy = orderBy;
						data.fSourceArrivalId=_id;
						return data;
					},
					dataType : 'JSON',//数据类型
					uniqueId : "id",//每一行的唯一标识，一般为主键列
					columns : [{
						checkbox : true
					},{
						field : 'fBillNo',
						align : 'center',
						valign: 'middle',
						sortable : true,
						title : '采购单号',
						visible : true,
						must:true,
						width: '10%',
						edit:false
					}, {
						field : 'fSupplyName',
						align : 'center',
						valign: 'middle',
						sortable : true,
						title : '供应商',
						visible : true,		
						width: '10%',
						edit:false
					}, {
						field : 'fEntryID',
						align : 'center',
						valign: 'middle',
						sortable : true,
						title : '序号',
						visible : true,		
						width: '10%',
						edit:false,
						showSearch:false
					}, {
						field : 'fNumber',
						align : 'center',
						valign: 'middle',
						sortable : true,
						title : '物料代码',
						visible : true,		
						width: '10%',
						edit:false
					},{
						field : 'fName',
						align : 'center',
						valign: 'middle',
						sortable : true,
						title : '物料名称',
						visible : true,
						width: '10%',
						edit:false
					},{
						field : 'fModel',
						align : 'center',
						valign: 'middle',
						sortable : true,
						title : '规格型号',
						visible : true,		
						width: '10%',
						edit:false
					}, {
						field : 'fQty',
						align : 'center',
						valign: 'middle',
						sortable : true,
						title : '采购数量',
						visible : true,		
						width: '10%',
						edit:false,
						showSearch:false
					}, {
						field : 'fCommitQty',
						align : 'left',
						valign: 'left',
//						sortable : true,
						title : '到货数量',
						visible : true,
						sortable: true,
						width: '10%',
						edit:false,
						showSearch:false
					}, {
						field : 'fDate',
						align : 'center',
						valign: 'middle',
						title : '下单日期',
						formatter : isNull,
						visible : true,
						sortable: true,
						width: '10%',
						formatter:dateFormatter,
						edit:false
					}, {
						field : 'fArrivalDate',
						align : 'center',
						valign: 'middle',
						title : '预计到货日期',
						formatter : isNull,
						visible : true,
						sortable: true,
						width: '10%',
						formatter:dateFormatter,
						edit:false
					},{
						field : 'fStockQty',
						align : 'center',
						valign: 'middle',
						sortable : true,
						title : '入库数量',
						visible : true,
						width: '10%',
						edit:false,
						showSearch:false
					}],
					onClickRow : function(row, $element) {//行单击
					},
					onLoadSuccess:function(row, $element) {
						console.log(row);
					}
				});
			$("#inputCardModal").modal('show');
		},
		'click .delete' : function(e, value, row, index) {//替换按钮点击事件
			showSwal(
					'删除',
					'您确定删除吗？',
					'是的，确定删除',
					function(result){
						if(result.value){
							showLoading();//显示正在提交中
							$.ajax({
								url : pathUrl("stockArrival/revokePoOrderArrival.action"),
								type : "POST",
								dataType : "JSON",
								data : { 'id':row.id},
								success : function(data) {
									if (data.code == "0000") {
										$("#inTable").bootstrapTable('refresh');
										swal_Tips_Short(data.message);
									} else if (data.code == "9999") {
										swal_Tips(data.message);
									}
								},
								error : function(request) {
									swal_Tips_Error();
								},
								complete: function () {
								}
							});
						}
					}
				)
			}
};

var resetColumn = [ 
	{
		checkbox : true
	},{
		field : 'fCode',
		align : 'left',
		valign: 'middle',
		sortable : true,
		title : '收料通知单',
		visible : true,
		must:true,
		width: '10%',
		edit:false
	},{
		field : 'fBillNo',
		align : 'left',
		valign: 'middle',
		sortable : true,
		title : '采购单号',
		visible : true,
		must:true,
		width: '10%',
		edit:false
	},{
		field : 'fSupplyName',
		align : 'left',
		valign: 'middle',
		sortable : true,
		title : '供应商',
		visible : true,		
		width: '10%',
		edit:false
	}, {
		field : 'fNumber',
		align : 'left',
		valign: 'middle',
		sortable : true,
		title : '物料代码',
		visible : true,		
		width: '10%',
		edit:false
	},{
		field : 'fName',
		align : 'left',
		valign: 'middle',
		sortable : true,
		title : '物料名称',
		visible : true,
		width: '10%',
		edit:false
	},{
		field : 'fModel',
		align : 'left',
		valign: 'middle',
		sortable : true,
		title : '规格型号',
		visible : true,		
		width: '10%',
		edit:false
	}, {
		field : 'fQty',
		align : 'left',
		valign: 'middle',
		sortable : true,
		title : '到货数量',
		visible : true,		
		width: '10%',
		edit:false,
		showSearch:false
	},  {
		field : 'fAuxQty',
		align : 'left',
		valign: 'middle',
		sortable : true,
		title : '辅助到货数量',
		visible : true,		
		width: '10%',
		edit:false,
		showSearch:false
	},{
		field : 'fWorkerName',
		align : 'left',
		valign: 'middle',
//		sortable : true,
		title : '接收人',
		visible : true,
		sortable: true,
		width: '10%',
		edit:false
	}, {
		field : 'fDate',
		align : 'left',
		valign: 'middle',
		title : '制单日期',
		formatter : isNull,
		visible : true,
		sortable: true,
		width: '10%',
		formatter:dateFormatter,
		edit:false
	}, {
		field : 'operate',
		align : 'left',
		valign: 'middle',
		title : '操作',
		formatter : isNull,
		visible : true,
		sortable: true,
		width: '10%',
		must:true,
		formatter : function(value,row,index){
			return '<button type="button" class="btn btn-default in" style="font-size:12px;margin-right:5px;">替换</button>'+
			'<button type="button" class="btn btn-default delete" style="font-size:12px;margin-right:5px;">删除</button>';
		},
		events : operateEvents,
		edit:false,
		showSearch:false
	}];
var dataExport = {/*
	'fDate' : $("#fDate").val(),*/
	'fOperation' : $("#fOperation").val(),
	'fMethod' : $("#fMethod").val(),
	'fIP' : $("#fIP").val(),
	'fLevel' : $("#fLevel").val(),
	'fParams' : $("#fParams").val(),
	'fBillerName' : $("#fBillerName").val(),
	'fExplanation' : $("#fExplanation").val(),
	'row' : 10000000
};

var colArr = [];
/*
 * @Description: 预加载 
 * @param :
 */
$(function (){
	resizeIframeHight();
//	initTable();
	initField();
	loadRecordName("CGDH",initTable);
	$(".CGDH",parent.document).click(function(){
		$('#inTable').bootstrapTable('refresh');
	});
});

/*
 * @Description: 初始化委外转出/接收表
 * @param : 
 */
function initTable(){
	$("#inTable").bootstrapTable('destroy').bootstrapTable({
		url : pathUrl("stockArrival/getStockArrivalList.action"),
		height : $(window).height()*0.78,//行高
		method : "POST",
		striped : true,
		cache : false,
//		editable:false,//开启编辑模式
		sidePagination : "server", // 分页方式：client客户端分页，server服务端分页（*）
		pagination : true,
		pageNumber : 1,
		pageSize : 10,
		pageList : [ 10, 30, 60, 100, 'ALL' ],
		dataExport : dataExport,
		showExport: true,
		colArr : colArr,
		exportDataType: "allServer",
		buttonsAlign:"right",  //按钮位置
		rowStyle : function(row, index) {
			var classes = [ 'success' ];
			if (index == rowIndex) {
				return {
					classes : classes[0]
				};
			}
			return {};
		},
		queryParams : function(params) {
			var data = {};
			var orderBy = params.sort + " " + params.order;      //排序列名
			if(params.sort==undefined){
				orderBy = "fDate desc";
			}
			data.offset = params.offset +1;
			data.row = params.limit,
			data.sqlStr = sqlCombine;
			data.orderBy = orderBy;
			return data;
		},
		dataType : 'JSON',
		uniqueId : "id",
		columns : customColumn,
		onClickRow: function (row,$element) {
//			console.log(row)
			$('.success').removeClass('success');// 去除之前选中的行的，选中样式
			$($element).addClass('success');// 添加当前选中的 success样式用于区别
			index = $element.data('index');
			rowIndex = index;
			_index = index;
			page = $('.pagination .active').find("a").eq(0).text();
		},
		onLoadSuccess:function(data){
			console.log(data);
		},
		onPageChange : function(number, size) {
			if (page == number) {
				rowIndex = index;
			} else {
				$('.success').removeClass('success');
				rowIndex = "%^%%%%";
			}
		},
		exportHandler : function(text){
			if(text == 'success'){
				$('#export').text('导出成功');
				setTimeout(function(){
					$('#export').text('导出');
					$('#export').blur();
					$('#export').removeAttr('disabled');
				},3000)
			}
		}
	});
}

/*
 * @Description: 重置按钮点击事件 
 * @param :
 */
$(".resetting").click(function(){
	$(".clean_C").val("");
	var data = dataExport;
	for(prop in data){
		if(data.hasOwnProperty(prop)){
			data[prop] = '';
		}
	}
	reset();
});

/*
 * @Description: 重置
 * @param :
 */
function reset(){
	$("#infoTable").bootstrapTable('destroy'); 
	initTable();
	$('.success').removeClass('success');
	rowIndex = "%^%%%%";
}
/*
 * @Description: more按钮点击事件
 * @param : 
 */
$("#more").click(function(){
	if(flag){
		$("#more").text("隐藏");
		$("#extend").show();
		flag = false;
	}else{
		$("#more").text("更多");
		$("#extend").hide();
		flag = true;
	}
	$('#inTable').bootstrapTable('resetWidth');
});

/*
 * @Description: 数据内容更改赋值给dataExport
 * @param :
 */
$('.page-heading .clean_C').on('change',function(){
	var attr = $(this).attr('name');
	dataExport[attr] = $(this).val();
});
/*
 * @Description: 导出按钮点击事件
 * @param :
 */
$('#export').click(function(e){
	$('#inTable').exportColumn();
});

/*
 * @Description: 查询条件按回车事件
 * @param :
 */
$("#fDate,#fOperation,#fMethod,#fIP,#fLevel,#fParams,#fBillerName,#fExplanation").keypress(function(event){
	if(event.keyCode == "13"){
		initTable();
	}
});

/*
 * @Description: 空字符串格式化
 * @param :
 */
function isNull(value,row,index){
	if(value == null){
		return "";
	}else{
		return value;
	}
}

function hideRow(){
	var length = $(".warning").length;
	if(value == 0 && length != 0){
		for(var x = 0;x < length;x++){
			document.getElementsByClassName("warning")[x].style.display = "none";//隐藏fIsMerge=2
		}
	}
}

/*
 * @Description: 员工ID输入框输入事件：输入员工ID后，自动带出员工姓名
 * @param : 
 */
validateID("#fWorker","#fWorkerName","#save");
/*
 * @Description: 替换1确认
 * @param : 
 */
$("#confirm").click(function() {
	/*var flag = 1;
	var ids=[];
	var datas = $("#daoTable").bootstrapTable('getSelections');//获取勾选的row
	$.each(datas,function(key,value){
		ids.push(value.id);
	});
	if(ids.length == 0){
		flag = 0;
		swal_Tips("请至少选择一个需要打印的物料项");
		return;
	}
	if(flag == 1){
		$("#useModal").modal('hide');
		$('#pickTable').bootstrapTable('refresh');
		window.open(pathUrl("OSL?ids="+ids+"&type=0"));
	}*/
	var dataJson=[];
	var daoData = [];
	var daojson = [];
	var fSupplyName;
	var _getData = $('#daoTable').bootstrapTable('getSelections'); 
	console.log(_getData);
	$.each(_getData,function(key,value){
		daoData = {
				"fEntryID":value.fEntryID,
				"fNumber":value.fNumber,
				"fName":value.fName,
				"fModel":value.fModel,
				"fQty":value.fQty,
				"fArrivalDate":value.fArrivalDate,
				"fCommitQty":value.fCommitQty,
				"fAuxCommitQty":value.fAuxCommitQty,
				"fStockID":value.fStockID,
				"fSourceInterId":value.fSourceInterId,
				"fSourceEntryID":value.fSourceEntryID,
				"fClosed":value.fClosed,
				"fDetailID":value.fDetailID,
				"fSecCoefficient":value.fSecCoefficient,
				"fTaxrate":value.fTaxrate,
				"fTaxPrice":value.fTaxPrice,
				"fPrice":value.fPrice,
				"fUnitName":value.fUnitName,
				"fTemp1Qty":value.fTemp1Qty,
				"fTempQty":value.fTempQty
		}
		//console.log(daoData);
		daojson.push(daoData);
		dataJson.push(value.fSupplyName);
		_fBillNo=value.fBillNo;
		_fDetailID=value.fDetailID;
		_fDate=value.fDate;
		_fSupplyName=value.fSupplyName;
		_fTaxrate=parseFloat((value.fTaxrate)/100);
	});
	if(_getData.length>1){
		swal_Tips("只能选择一个,请重新勾选");
		return false;
	}
	$("#infTranOutQty").val(dateFormatter(_fDate));
	$("#infSupplierName").val(_fSupplyName);
	$('#tiTable').bootstrapTable('destroy').bootstrapTable({
		pagination : false,//是否显示分页
		clickToSelect : true,//是否启用点击选中行
		/*singleSelect : true,//是否单选
*/		pageNumber : 1,//初始化加载第几页
		pageSize : 5,//每页的记录行数
		//sidePagination : "server", // 分页方式：client客户端分页，server服务端分页（*）
		pageList : [ 5, 15, 30, 50, 100 ],// 分页方式：client客户端分页，server服务端分页
		queryParams : function(params) {//传递参数
			var data= {};
			data.offset = params.offset;
			data.row = params.limit;
			//data.sortOrder = params.order;//排序
			//data.sortName = params.sort;//排序
			//data.fBillNo = _fBillNo;
			return data;
		},
		dataType : 'JSON',//数据类型
		uniqueId : "id",//每一行的唯一标识，一般为主键列
		columns : [ {
			checkbox : true
		}, {
			field : 'fEntryIDs',
			align : 'center',
			valign: 'middle',
			title : '序</br>号',
			edit:false,
			formatter: function (value, row, index) {
		        return index+1;
		    }
		},{
			field : "fNumber",
			align : 'center',
			valign: 'middle',
			title : '物料代码',
			edit : false
		}, {
			field : "fName",
			align : 'center',
			valign: 'middle',
			title : '物料名称',
			edit : false
		}, {
			field : "fModel",
			align : 'center',
			valign: 'middle',
			title : '规格型号',
			edit : false
		}, {
			field : "fQty",
			align : 'center',
			valign: 'middle',
			title : '采购</br>数量',
			edit : false
		}, {
			field : "fArrivalDate",
			align : 'center',
			valign: 'middle',
			title : '预计</br>到货</br>日期',
			formatter :dateFormatter,
			edit : false
		}, {
			field : "fSecCoefficient",
			align : 'center',
			valign: 'middle',
			title : '换</br>算</br>率',
			edit : false
		}, {
			field : "fUnitName",
			align : 'center',
			valign: 'middle',
			title : '单</br>位',
			edit : false
		}, {
			field : "fCommitQty",
			align : 'center',
			valign: 'middle',
			title : '已</br>到</br>数',
			edit : false
		}, {
			field : "fStockID",
			align : 'center',
			valign: 'middle',
			title : '仓库',
			width : 100,
			edit : {
				type : 'select',// 下拉框
		    	url : pathUrl("stock/getStockList.action"),
				method : 'POST',//请求方式（必填）
		    	valueField : 'fStockID',
		    	textField : 'fStockName',
		    	onSelect : function(val,rec){
//		    		console.log(val,rec)
		    		var $tr = $(this)[0].$el.closest("tr");
		    		var index = $tr.data('index');
		    		var row = {};
		    		row.fStockID = val;
					$('#tiTable').bootstrapTable('updateRow',{index: index,row:row});
		    	}
			}
		},  {
			field : "fTempQty",
			align : 'center',
			valign: 'middle',
			title : '到</br>货</br>数',
			edit : true,
			formatter : function(value,row,index){
				if(value == undefined){
					return '';
				}else{
					return value;
				}
			},
			
		},  {
			field : "fTemp1Qty",
			align : 'center',
			valign: 'middle',
			title : '辅助</br>到货</br>数',
			edit : true,
			formatter : function(value,row,index){
				gg=row.fNumber.substring(0,2);
				orderNumbert = index;
				if(value == ""){
					return "";
				}else{
					return parseFloat(value);
				}
			}
			
		}, {
			field : "fPrice",
			align : 'center',
			valign: 'middle',
			title : '单</br>价',
			edit : true,
			formatter : function(value,row,index){
				orderNumber = index;
				if(value == ""){
					return "";
				}else{
					return parseFloat(value);
				}
			}
		}, {
			field : "fTaxPrice",
			align : 'center',
			valign: 'middle',
			title : '含税</br>单价',
			edit : true,
		},{
			field : 'fClosed',//如需导出execl field必填operate，否则操作行会被导出
			align : 'center',
			valign: 'middle',
			title : '是否</br>关闭',
			edit:{
				type : 'select',// 下拉框
		    	data : [{id:"1",text:'是'},{id:'0',text:'否'}]
			}
		}],
		onClickRow : function(row, $element) {//行单击
		}
	});
	$('#tiTable').bootstrapTable('load', daojson);
	$("#inputCards").modal('show');

})
/*
 * @Description: 修改对应事件
 * @param :
 */

$("#tiTable").on('editable-save.bs.table',function($el,field, row, oldValue){
	var markss=true;
	var value = {};
	row.fTaxPrice = (parseFloat(row.fPrice)*_fTaxrate+parseFloat(row.fPrice))*10000000;
	row.fTaxPrice = Math.round(row.fTaxPrice)/10000000;
	$('#tiTable').bootstrapTable('updateRow',{index: orderNumber,row:value});
	if(row.fSecCoefficient == 0){
		markss=false;
		if(row.fTemp1Qty!=0){
			swal_Tips("换算率为0，辅助到货数不能修改");
			console.log('llll');
			row.fTemp1Qty=0;
			return false;
		}
	}
	/*if(row.fCommitQty>0){
		markss=false;
	}*/
	else{
		row.fTempQty = (parseFloat(row.fTemp1Qty)*parseFloat(row.fSecCoefficient))*10000000;
		row.fTempQty = Math.round(row.fTempQty)/10000000;
	}
	if(markss){
		$('#tiTable').bootstrapTable('updateRow',{index: orderNumbert,row:value});
	}
	else{
		console.log('false');
	}
})
/*
 * @Description: 替换2确认
 * @param : 
 */
$("#gotodo").click(function() {
	var flag = 1;/*
	var dataJson=[];
	var datass={};*/
	var tidata={};
	var tidatajson=[];
	var datas = $("#tiTable").bootstrapTable('getSelections');//获取勾选的row
	var _fDetailID,_fArrivalDate,_fArrivalQty,_fAuxQty,_fIsColsed,_fStockID,_fName,_fModel,_fNumber,_fSecCoefficient,_fTaxrate,_fTaxPrice,_fPrice;
	$.each(datas,function(key,value){
		_fDetailID=value.fDetailID;
		_fArrivalDate=dateFormatter(value.fArrivalDate)+":00";
		_fArrivalQty=value.fTempQty;
		_fAuxQty=value.fTemp1Qty;
		_fIsColsed=value.fClosed;
		_fStockID=value.fStockID;
		_fName=value.fName;
		_fModel=value.fModel;
		_fNumber=value.fNumber;
		_fSecCoefficient=value.fSecCoefficient;
		_fTaxrate=value.fTaxrate;
		_fTaxPrice=value.fTaxPrice;
	});
	if(flag == 1){
		showLoading();
		console.log( JSON.stringify(tidatajson));
		$.ajax({
			url : pathUrl("stockArrival/replacePoOrderArrival.action"),
			type : "POST",
			dataType : "JSON",
			data : {
				'fSourceArrivalId':_id,"fSPID":0,"fWorker":$('#fWorker').val(),"fDetailID":_fDetailID,
				"fArrivalQty":parseInt(_fArrivalQty),"fAuxQty":parseInt(_fAuxQty),"fIsColsed":_fIsColsed,"fStockID":_fStockID,"fName":_fName,
				"fModel":_fModel,"fNumber":_fNumber,"fSecCoefficient":_fSecCoefficient,"fTaxrate":_fTaxrate,"fTaxPrice":_fTaxPrice,"fPrice":_fPrice
			},
			success : function(data) {
				if (data.code == "0000") {
					console.log(data);
					swal_Tips_Short(data.message);
					$("#inputCards").modal('hide');
					$('#tiTable').bootstrapTable('refresh');
					$(".clean_C").val("");
				} else if (data.code == "9999") {
					swal_Tips(data.message);
				}
			},
			error : function(request) {
				swal_Tips_Error();
			},
			complete : function () {
			}
		});
		}
})